package com.xyzwps.server.paimon.common

import jakarta.servlet.http.HttpServletRequest
import org.springframework.graphql.server.WebGraphQlRequest

class TokenGetter {

    private val cookieGetterFn: (String) -> String?
    private val headerGetterFn: (String) -> String?

    constructor(request: HttpServletRequest) {
        cookieGetterFn = { name -> request.cookies?.find { it.name == name }?.value }
        headerGetterFn = { name -> request.getHeader(name) }
    }

    constructor(request: WebGraphQlRequest) {
        cookieGetterFn = { name -> request.cookies[name]?.firstOrNull()?.value }
        headerGetterFn = { name -> request.headers[name]?.firstOrNull() }
    }

    val token: String?
        get() {
            val auth = headerGetterFn("Authorization")
            if (auth != null && auth.startsWith("Bearer ")) {
                return auth.substring(7)
            }

            val token = cookieGetterFn("token")
            if (token != null) {
                return token
            }

            return null
        }
}
